﻿function getHtml(html) {
    while (html.indexOf('_getLayout') != -1) {
        html = replaceFunc(html);
    }
    return html;
}
function _getLayout(layoutId) {
    var query = new breeze.EntityQuery
          .from('AppLayouts')
          .where('UniqueId', '==', layoutId);
    var customers = manager.executeQueryLocally(query);
    return customers[0].Html();
}
function replaceFunc(str) {
    var resl = str.split("_getLayout(");
    var parameters = Array();
    for (var i = 1; i < resl.length; i++) {
        parameters.push(resl[i].substr(0, resl[i].indexOf(')')));
        resl[i] = resl[i].substr(resl[i].indexOf(')') + 1, resl[i].length);
    }
    var html = resl[0];
    for (var j = 1; j < resl.length; j++) {
        html += "<div id='idte_" + parameters[j - 1] + "'>" + _getLayout(parameters[j - 1]) + "</div>";
        html += resl[j];
    }
    return html;
}
function clearLayout() {
    $('#contain').html('');
}
function elementDrag() {
    $(".eledrag").draggable({
        helper: 'clone',
        cursor: "move"
    });
    $(".basicdrag").draggable({
        helper: 'clone',
        cursor: "move"
    });
    $(".eledrop").droppable({
        activeClass: "ui-state-hover",
        hoverClass: "ui-state-active",
        greedy: true,
        drop: function (event, ui) {
            if ($(ui.draggable[0]).hasClass('basic')) {
                var newTag = jQuery("<" + ui.draggable[0].innerText + " class='minimal eledrop' />");
                $(this).append(newTag);
                elementDrag();
                eventReg();
                return;
            }
            if ($(ui.draggable[0]).hasClass('advance')) {
                var id = $(ui.draggable[0].nextElementSibling).find(":selected").val();
                var html = getHtml(_getLayout(id));
                var newTag = jQuery("<div id='idte_" + id + "' />");
                newTag.append(html);
                $(this).append(newTag);

            } else {
                vm.AdvanceCom([]);
                clearLayout();
                var element = ko.dataFor(ui.draggable[0]);
                for (var i = 0; i < element.Parent().length; i++) {
                    vm.AdvanceCom.push(element.Parent()[i]);
                }

                vm.TypeObser = element;
                ko.cleanNode($('#two')[0]);
                vm.SelectedLayout(undefined);
                ko.applyBindings(vm, $('#two')[0]);
                elementDrag();
            }

        }
    });

}
var curE;
function removeComponent() {
    $(curE).remove();
}
function eventReg() {
    $("#_height").change(function () {
        $(curE).height($("#_height").val());
    });
    $("#_width").change(function () {
        $(curE).width($("#_width").val());
    });
    $(".minimal").click(function (e) {
        curE = $(this);
        $('#_id').val(this.id);
        $('#_title').val(this.title);
        $('#_height').val($(this).height());
        $('#_width').val($(this).width());

        var list = $('.focus');
        for (var i = 0; i < list.length; i++) {
            $(list[i]).removeClass('focus');
        }
        $(this).focus().addClass('focus');
        e.stopPropagation();
    });
}
function removeClass(str) {
    var strHtml = str.split('class="');
    for (var i = 1; i < strHtml.length; i++) {
        var index = strHtml[i].indexOf('"');
        strHtml[i] = strHtml[i].substr(index + 1);
    }
    return strHtml.join('');
}
function generateHtml() {
    var html = "<div>" + $('#contain').html() + "</div>";
    $(html).find('div[id*=idte_]').each(function () {
        var a = $(this)[0].outerHTML;
        var b = "_getLayout(" + this.id.substr(5) + ")";
        html = html.replace(a, b);
    });
    html = removeClass(html);
    return $(html).html();
}
function saveLayout() {
    if (!(typeof vm.SelectedLayout() === "undefined")) {
        var tmp = generateHtml();
        var index = $("#selectedlay option:selected").index();
        vm.TypeObser.AppLayouts()[index - 1].Html(tmp);
        Save();
    } else {
        var LayoutName = prompt("Please enter Layout name", "Layout name");
        if (LayoutName != null && LayoutName.trim().length > 0) {
            var newLayout = manager.createEntity("AppLayout", { LayoutName: LayoutName, Html: generateHtml(), AppId: vm.TypeObser.UniqueId() });
            vm.TypeObser.AppLayouts().push(newLayout);
            Save();
        } else {
            alert("Invalid name!. Save's canceled.");
        }
    }
}